<template>
  <div class="major-explorer">
    <div class="page-header">
      <h2>专业探索</h2>
    </div>

    <div class="explorer-content">
      <!-- 左侧专业目录树 -->
      <div class="category-tree card">
        <el-tabs v-model="viewMode" style="height: 100%">
          <el-tab-pane label="列表视图" name="list" style="height: 100%">
            <div class="search-box">
              <el-input v-model="searchQuery" placeholder="搜索专业名称" clearable @input="handleSearch">
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            <el-tree
              :data="filteredTree"
              :props="defaultProps"
              @node-click="handleNodeClick"
              :highlight-current="true"
              :default-expanded-keys="expandedKeys"
              style="height: calc(100% - 50px); overflow-y: auto"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span>{{ node.label }}</span>
                  <span class="count">({{ data.value }})</span>
                </span>
              </template>
            </el-tree>
          </el-tab-pane>
          <el-tab-pane label="树图视图" name="tree" style="height: 100%">
            <MajorTreeChart
              :data="majorTree"
              v-model:currentMajor="currentMajor.title"
              :cur-first-major="curFirstMajor"
              :active="viewMode === 'tree'"
            />
          </el-tab-pane>
        </el-tabs>
      </div>

      <div class="content-area">
        <div class="charts-container">
          <div class="chart-item card">
            <!-- 专业分布 -->
            <MajorDistribution
              v-model:currentMajor="currentMajor.title"
              :initial-category="currentMajor.level === 'level1' ? currentMajor.title : ''"
              :initial-sub-category="currentMajor.level === 'level2' ? currentMajor.title : ''"
            />
          </div>
          <div class="chart-item card">
            <!-- 专业智能分析 -->
            <MajorAnalysis v-if="currentMajor" :major-code="currentMajor.key" :major-name="currentMajor.title" />
          </div>
        </div>

        <!-- 专业词云 -->
        <div class="word-cloud card">
          <MajorWordCloud v-model:currentMajor="currentMajor.title" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from "vue"
import { MajorWordCloud, MajorDistribution } from "@/components"
import { getMajorTreeDataApi, getMajorCategoriesApi } from "@/interface"
import MajorTreeChart from "@/components/charts/MajorTreeChart.vue"
import MajorAnalysis from "@/components/charts/MajorAnalysis.vue"
import { Search } from "@element-plus/icons-vue"

// 专业目录树数据
const majorTree = ref<Record<string, any>[]>([])
const filterLevel = ref("level0")
const filterCode = ref("")
const viewMode = ref("list")
const currentMajor = ref<any>({
  key: "",
  title: "软件工程"
})

const defaultProps = ref({
  children: "children",
  label: "title"
})

const curFirstMajor = ref(majorTree.value[0]?.title ?? "")

// 搜索相关
const searchQuery = ref("")
const filteredTree = ref<Record<string, any>[]>([])
const expandedKeys = ref<string[]>([])

// 处理搜索
const handleSearch = () => {
  if (!searchQuery.value) {
    filteredTree.value = majorTree.value
    expandedKeys.value = []
    return
  }

  const search = (nodes: any[], parentKeys: string[] = []): any[] => {
    return nodes.filter(node => {
      const currentKeys = [...parentKeys, node.key]
      const match = node.title.toLowerCase().includes(searchQuery.value.toLowerCase())
      let shouldKeep = match

      if (node.children) {
        const matchedChildren = search(node.children, currentKeys)
        if (matchedChildren.length > 0) {
          node.children = matchedChildren
          shouldKeep = true
          // 如果子节点有匹配，将当前节点添加到展开列表中
          if (!expandedKeys.value.includes(node.key)) {
            expandedKeys.value.push(node.key)
          }
        }
      }

      if (shouldKeep) {
        // 如果当前节点匹配，确保所有父节点都被展开
        parentKeys.forEach(key => {
          if (!expandedKeys.value.includes(key)) {
            expandedKeys.value.push(key)
          }
        })
      }

      return shouldKeep
    })
  }

  expandedKeys.value = []
  filteredTree.value = search([...majorTree.value])
}

// 监听搜索词变化
watch(searchQuery, () => {
  handleSearch()
})

// 监听majorTree变化
watch(majorTree, () => {
  handleSearch()
})

const handleNodeClick = async (data: any) => {
  console.log("点击节点数据:", data)
  filterLevel.value = data.level
  filterCode.value = data.key

  // 更新当前选中的专业（用于图表显示）
  currentMajor.value = {
    key: data.key,
    title: data.title,
    level: data.level
  }

  if (data.level === "level1") {
    console.log("点击一级分类:", data.title)
    curFirstMajor.value = data.title
    // 获取该一级学科下的专业树数据
    const res: any = await getMajorCategoriesApi(data.title)
    if (res?.data?.data) {
      // 保持原有的树结构，只更新数据
      const newTree = [...majorTree.value]
      const index = newTree.findIndex(item => item.key === data.key)
      if (index !== -1) {
        newTree[index] = {
          ...newTree[index],
          children: res.data.data
        }
      }
      majorTree.value = newTree
    }
  }
}

onMounted(() => {
  getMajorTreeDataApi().then((res: any) => {
    majorTree.value = res.tree
    curFirstMajor.value = majorTree.value[0]?.title ?? ""
  })
})
</script>

<style lang="scss" scoped>
.major-explorer {
  height: 100%;
  width: 100%;

  .page-header {
    @include flex-between;
    margin-bottom: 20px;
    height: 40px;

    .header-tools {
      display: flex;
      gap: 10px;
    }
  }

  .explorer-content {
    display: flex;
    gap: 20px;
    height: calc(100% - 60px);

    .category-tree {
      flex: 0 0 300px;
      overflow-y: auto;

      .search-box {
        padding: 10px;
        border-bottom: 1px solid #ebeef5;
      }
    }

    .content-area {
      display: flex;
      flex-direction: column;
      gap: 20px;
      flex: 1;
      height: 100%;

      .word-cloud {
        flex: 1 1 50%;
        height: 100%;
      }

      .major-list {
        flex: 1;
        overflow-y: auto;
      }

      .charts-container {
        flex: 1 1 50%;
        display: flex;
        gap: 20px;
        min-height: 0;

        .chart-item {
          flex: 1;
          h4 {
            margin-bottom: 15px;
            color: #333;
          }
        }
      }
    }
  }
}

.card {
  @include card;
}
</style>
